<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="conditionType" style="width: 170px; margin-right: 2px;">
          <el-option label="订单号" value="orderCode">订单号</el-option>
          <el-option label="客户电话" value="contactPhone">客户电话</el-option>
          <el-option label="客户编号" value="csmCode">客户编号</el-option>
          <el-option label="客户名称" value="csmName">客户名称</el-option>
          <el-option label="客户地址" value="csmAddress">客户地址</el-option>
          <el-option label="备注" value="remark">备注</el-option>
          <el-option label="商品描述" value="goodsDesc">商品描述</el-option>
          <el-option label="销售员" value="saleMan">销售员</el-option>
          <el-option label="镂空码" value="unifiedCode">镂空码</el-option>
        </el-select>
        <el-input v-model.trim="csmText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="订单来源:" prop="orderSource">
        <el-select v-model="query.orderSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orderSourceMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类型:">
        <el-select v-model="query.csmType" clearable placeholder="请选择">
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="签收时间:" :table-form-merge="2">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item label="所属机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
      </el-form-item>
      <el-form-item label="配送员:">
        <el-select v-model="query.ownerId" filterable clearable :loading="$loadingPlugin.getOwnersList" style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:">
        <el-select v-model="query.paymentMethod" filterable clearable placeholder="请选择">
          <el-option v-for="(l) in paymentMethodMap" :key="l.value" :label="l.desc" :value="l.value" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>

    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" @click="exportEX">导出</el-button>
        <el-checkbox v-model="query.equals" style="margin-left: 10px;" @change="checkboxChange">应收不等于实收</el-checkbox>
      </div>
      <div style="font-size: 14px; line-height: 32px;">
        {{ message }}
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <location ref="location" />
    <bottleDetail ref="bottleDetail" />
    <OrderFlowInfoModal ref="OrderFlowInfoModal" />
  </div>
</template>

<script>
  import { queryOrderManageList, queryMap, queryOwnersList, queryOrderListExport } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import BottleDetail from '../../components/BottleDetail'
  import Location from '../../components/CsmLocation'
  import OrderFlowInfoModal from '../../components/OrderFlowInfoModal'

  export default {
    name: 'receiptManage',
    components: {
      Location,
      BottleDetail,
      OrderFlowInfoModal
    },
    data() {
      return {
        treeData: [],
        message: '',
        ownersList: [],
        paymentMethodMap: [],
        orderSourceMap: [],
        customerTypeMap: [],
        conditionType: 'contactPhone',
        csmText: '',
        date: [moment().startOf('day'), moment().endOf('day')],
        query: {
          orderSource: [0],
          csmType: '',
          orgSNNo: '', // 所属机构orgSNNo
          ownerId: '',
          paymentMethod: '',
          equals: false
        },
        roleTypeList: [],
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              fixed: true,
              align: 'center'
            },
            {
              prop: 'orderCode',
              label: '订单号',
              width: 110
            },
            {
              prop: 'fromPlat',
              label: '订单来源',
              render: (h, { row }) => <span>{ row.fromPlat && formatColumnMap(this.orderSourceMap, 'value', row.fromPlat, 'desc') }</span>
            },
            {
              prop: 'signDt',
              label: '签收时间',
              width: 160,
              render: (h, { row }) => <span>{ row.signDt && parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'csmCode',
              label: '客户编号'
            },
            {
              prop: 'csmName',
              label: '客户名称'
            },
            {
              prop: 'csmType',
              label: '客户类型',
              render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') }</span>
            },
            {
              prop: 'csmPhone',
              label: '呼叫电话',
              width: 110
            },
            {
              prop: 'orgName',
              label: '责任机构',
              width: 160
            },
            {
              prop: 'sfzh',
              label: '身份证号',
              width: 180
            },
            {
              prop: 'contact',
              label: '联系人'
            },
            {
              prop: 'contactPhone',
              width: 110,
              label: '联系电话'
            },
            {
              prop: 'csmAddress',
              label: '联系地址',
              width: 180
            },
            {
              prop: 'goodsCount',
              align: 'right',
              label: '商品总数'
            },
            {
              prop: 'goodsDesc',
              label: '商品描述',
              width: 180
            },
            {
              prop: 'treceivables',
              width: 100,
              align: 'right',
              label: '应收总金额'
            },
            {
              prop: 'taccReceivable',
              width: 100,
              label: '实收总金额',
              align: 'right'
            },
            {
              prop: 'paymentMethod',
              label: '支付方式',
              align: 'center',
              render: (h, { row }) => <span>{ row.paymentMethod && formatColumnMap(this.paymentMethodMap, 'value', row.paymentMethod, 'desc') }</span>
            },
            {
              prop: 'recChipCount',
              align: 'right',
              label: '轻瓶数量'
            },
            {
              prop: 'newChipCount',
              label: '重瓶数量',
              align: 'right'
            },
            {
              prop: 'relBackGas',
              label: '回收气量',
              align: 'right'
            },
            {
              prop: 'generalGas',
              width: 100,
              label: '实际送气量',
              align: 'right'
            },
            {
              prop: 'ownerName',
              label: '配送员'
            },
            {
              prop: 'carNumber',
              label: '配送车辆'
            },
            {
              prop: 'transactor',
              label: '下单人'
            },
            {
              prop: 'transactTime',
              label: '下单时间',
              width: 180,
              render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'dateTimeSpare3',
              label: '派送时间',
              width: 180,
              render: (h, { row }) => <span>{ row.dateTimeSpare3 && parseTime(row.dateTimeSpare3, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'remark',
              label: '备注',
              width: 180
            },
            {
              prop: 'saleMan',
              label: '销售员'
            },
            {
              prop: 'signUserName',
              label: '签收人'
            },
            {
              prop: 'signUserIdNumber',
              label: '签收人身份证号',
              width: 180
            },
            {
              prop: 'recGPBMIDS',
              label: '轻瓶钢瓶',
              width: 180,
              render: (h, { row }) => <el-link onClick={() => this.openDetail(row, 1)}>{row.recGPBMIDS}</el-link>
            },
            {
              prop: 'newGPBMIDS',
              label: '重瓶钢瓶',
              width: 180,
              render: (h, { row }) => <el-link onClick={() => this.openDetail(row, 2)}>{row.newGPBMIDS}</el-link>
            },
            {
              prop: 'recChipIDS',
              label: '轻瓶芯片',
              width: 180,
              render: (h, { row }) => <el-link onClick={() => this.openDetail(row, 1)}>{row.recChipIDS}</el-link>
            },
            {
              prop: 'newChipIDS',
              label: '重瓶芯片',
              width: 180,
              render: (h, { row }) => <el-link onClick={() => this.openDetail(row, 2)}>{row.newChipIDS}</el-link>
            },
            {
              prop: 'recUnifiedCodes',
              label: '轻瓶镂空码',
              width: 180,
              render: (h, { row }) => <el-link onClick={() => this.openDetail(row, 1)}>{row.recUnifiedCodes}</el-link>
            },
            {
              prop: 'newUnifiedCodes',
              label: '重瓶镂空码',
              width: 180,
              render: (h, { row }) => <el-link onClick={() => this.openDetail(row, 2)}>{row.newUnifiedCodes}</el-link>
            },
            {
              label: '操作',
              fixed: 'right',
              width: 150,
              render: (h, { row, $index }) => {
                return (
                    <div>
                      <el-link underline={false} size='mini' onClick={() => this.update(row, $index)}>
                        流转信息
                      </el-link>
                      <el-link underline={false} size='mini' onClick={() => this.openLocation(row, $index)}>
                        签收位置
                      </el-link>
                    </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData', 'exportDomain'
      ])
    },
    watch: {
      'query.orderSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderSource.length === this.orderSourceMap.length) this.query.orderSource = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      }
    },
    async created() {
      await Promise.all([this.queryOptionsMap(), this.getTreeData()])
    },
    methods: {
      // 导出
      exportEX() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryOrderListExport({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.$set(this.query, 'ownerId', '')
        this.getOwnersList(value.orgId)
      },
      // 查询处理人列表
      async getOwnersList(orgId) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnersList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data
      },
      closeTree() {
        this.$set(this.query, 'ownerId', '')
        this.ownersList = []
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          orderStatus: 10,
          currentPage,
          pageSize
        }
        query[this.conditionType] = this.csmText
        if (this.date && this.date.length > 0) {
          query.signTime = moment(this.date[0]).format()
          query.signTimeEnd = moment(this.date[1]).format()
        }
        if (this.query.orderSource[0] === 0) query.orderSource = []
        const res = await queryOrderManageList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        if (res.data.rows.length > 0) this.message = res.message
      },
      checkboxChange() {
        this.$refs.lbTable.fetch()
      },
      async openDetail(row, t) {
        await this.$refs.bottleDetail.open(row, t)
      },
      async openLocation(row) {
        await this.$refs.location.open(row)
      },
      // 流转信息
      async update(row) {
        await this.$refs.OrderFlowInfoModal.open(row.orderCode)
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }), mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }), mergeAsyncFunc(queryMap, { enumName: 'OrderSource' })])
        this.customerTypeMap = res1.data // 客户类型
        this.paymentMethodMap = res2.data // 支付方式
        this.orderSourceMap = res3.data // 订单来源
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .el-form-item .el-form-item {
    margin-bottom: 0;
  }
  .merge-item {
    /deep/ .el-form-item__content {
      display: flex;
    }
  }
  .btn-group {
    display: flex;
    justify-content: space-between;
  }
</style>
